import { defineStore } from 'pinia'
import { store } from '../index'
import { ElMessageBox } from 'element-plus'

import { useI18n } from '@/hooks/web/useI18n'
import { useStorage } from '@/hooks/web/useStorage'

import { loginApi, getCurrentUserInfoApi } from '@/api/login'
import { UserLoginType, UserType } from '@/api/login/types'

import { useAppStore } from './app'
import { useDictStore } from './dict'
import { usePermissionStore } from './permission'
import { useTagsViewStore } from './tagsView'

import router from '@/router'

const { clear } = useStorage()

interface UserState {
  userInfo?: UserType
  tokenKey: string // 提交认证请求时，设置的 header key
  token: string // 认证 token
  refreshToken: string // 刷新 token
  roles: string[] // 当前用户角色 role_key 列表
  permissions: string[] // 当前用户权限列表
  roleRouters?: string[] | AppCustomRouteRecordRaw[]
  rememberMe: boolean
  loginInfo?: UserLoginType
}

export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      userInfo: undefined,
      tokenKey: 'Authorization',
      token: '',
      refreshToken: '',
      roles: [],
      permissions: [],
      roleRouters: undefined,
      rememberMe: true,
      loginInfo: undefined
    }
  },
  getters: {
    getUserInfo(): UserType | undefined {
      return this.userInfo
    },
    getTokenKey(): string {
      return this.tokenKey
    },
    getToken(): string {
      return this.token
    },
    getRefreshToken(): string {
      return this.refreshToken
    },
    getRoles(): string[] {
      return this.roles
    },
    getPermissions(): string[] {
      return this.permissions
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return this.roleRouters
    },
    getRememberMe(): boolean {
      return this.rememberMe
    },
    getLoginInfo(): UserLoginType | undefined {
      return this.loginInfo
    }
  },
  actions: {
    setUserInfo(userInfo?: UserType) {
      this.userInfo = userInfo
    },
    setTokenKey(tokenKey: string) {
      this.tokenKey = tokenKey
    },
    setToken(token: string) {
      this.token = token
    },
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken
    },
    setRoles(roles: string[]) {
      this.roles = roles
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },
    setRoleRouters(roleRouters: string[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = roleRouters
    },
    setRememberMe(rememberMe: boolean) {
      this.rememberMe = rememberMe
    },
    setLoginInfo(loginInfo: UserLoginType | undefined) {
      this.loginInfo = loginInfo
    },
    async login(formData: UserType) {
      formData.platform = '0'
      const res = await loginApi(formData)
      if (res) {
        this.token = `${res.data.token_type} ${res.data.access_token}`
        this.refreshToken = res.data.refresh_token
        // 获取当前登录用户的信息
        await this.setCurrentUserInfo()
      }
      return res
    },
    // 获取用户详细信息，包括角色，权限
    // 用户信息取消使用持久化存储，仅使用共享存储
    async setCurrentUserInfo() {
      const res = await getCurrentUserInfoApi()
      this.userInfo = res.data
      this.roles = res.data.roles.map((item) => {
        if (!item.disabled) {
          return item.role_key
        }
      })
      this.permissions = res.data.permissions
    },
    logoutConfirm() {
      const { t } = useI18n()
      ElMessageBox.confirm(t('common.dialog.logoutMessage'), t('common.dialog.reminder'), {
        confirmButtonText: t('component.button.ok'),
        cancelButtonText: t('component.button.cancel'),
        type: 'warning'
      })
        .then(async () => {
          // const res = await logoutApi().catch(() => {})
          // if (res) {
          //   this.reset()
          // }
          this.reset()
        })
        .catch(() => {})
    },
    reset() {
      clear()

      const appStore = useAppStore()
      appStore.$reset()

      const dictStore = useDictStore()
      dictStore.$reset()

      const permissionStore = usePermissionStore()
      permissionStore.$reset()

      const tagsViewStore = useTagsViewStore()
      tagsViewStore.delAllViews()

      this.setToken('')
      this.setUserInfo(undefined)
      this.setRoleRouters([])
      router.replace('/login')
    },
    logout() {
      this.reset()
    }
  },
  persist: true
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
